<template>
  <div class="wrong-questions-page">
    <div class="page-header">
      <h2>错题集</h2>
      <p>查看您的错题，重点复习薄弱环节</p>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-controls">
        <el-select v-model="filterParams.examType" placeholder="考试类型" clearable style="width: 150px;">
            <el-option :label="item.name" :value="item.id" v-for="(item,index) in examTypes" />
            <!--<el-option label="全部" value=""  />-->
          <!--<el-option label="特定技能" value="特定技能" />-->
          <!--<el-option label="JFT" value="JFT" />-->
          <!--<el-option label="JLPT" value="JLPT" />-->
        </el-select>
        
        <!--<el-select v-model="filterParams.questionType" placeholder="题目类型" clearable style="width: 150px;">-->
          <!--<el-option label="全部" value="" />-->
          <!--<el-option label="单选题" value="singleChoice" />-->
          <!--<el-option label="多选题" value="multipleChoice" />-->
          <!--<el-option label="判断题" value="trueFalse" />-->
          <!--<el-option label="填空题" value="fillBlank" />-->
        <!--</el-select>-->
        <!---->
        <el-select v-model="filterParams.wrongCount" placeholder="错误次数" clearable style="width: 150px;">
          <el-option label="全部" value="" />
          <el-option label="1次" value="1" />
          <el-option label="2次" value="2" />
          <el-option label="3次以上" value="3+" />
        </el-select>
        
        <el-input
          v-model="filterParams.keyword"
          placeholder="搜索题目内容"
          style="width: 200px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.totalWrongQuestions }}</h3>
            <p>总错题数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><RefreshRight /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.reviewedQuestions }}</h3>
            <p>已复习题数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.masteredQuestions }}</h3>
            <p>已掌握题数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <h3>{{ stats.masteryRate }}%</h3>
            <p>掌握率</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 错题列表 -->
    <div class="questions-section">
      <div class="section-header">
        <h3>错题列表</h3>
        <!--<div class="actions">-->
          <!--<el-button type="success" size="small" @click="batchReview">-->
            <!--批量复习-->
          <!--</el-button>-->
          <!--<el-button type="warning" size="small" @click="exportWrongQuestions">-->
            <!--导出错题-->
          <!--</el-button>-->
        <!--</div>-->
      </div>
      
      <div class="questions-table">
        <el-table 
          :data="wrongQuestions" 
          style="width: 100%"
          v-loading="loading"
          :empty-text="emptyText"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="examName" label="考试名称" min-width="150">
            <template #default="scope">
              <div class="exam-name">
                <div>
                  <div class="exam-title">{{ scope.row.examTypeName }}</div>
                  <div class="exam-type">{{ scope.row.examName }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="question.content" label="题目内容" min-width="300">
            <template #default="scope">
              <div class="question-content">
                <div class="question-text">{{ scope.row.questionName }}</div>
                <div class="question-meta">
                  <!--<el-tag size="small" type="info">{{ getQuestionTypeText(scope.row.question.type) }}</el-tag>-->
                  <el-tag size="small" type="warning">错误{{ scope.row.wrongTimes }}次</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="userAnswer" label="您的答案" width="120">
            <template #default="scope">
              <span class="user-answer">{{ formatAnswer(scope.row.wrongAnswer ) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="question.correctAnswer" label="正确答案" width="120">
            <template #default="scope">
              <span class="correct-answer">{{ formatAnswer(scope.row.correctAnswer) }}</span>
            </template>
          </el-table-column>
          
          <!--<el-table-column prop="lastWrongTime" label="最近错误" width="150">-->
            <!--<template #default="scope">-->
              <!--{{ formatDateTime(scope.row.lastWrongTime) }}-->
            <!--</template>-->
          <!--</el-table-column>-->
          <!---->
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small"
                @click="reviewQuestion(scope.row)"
              >
                复习此题
              </el-button>
              <el-button 
                type="info" 
                size="small"
                @click="viewExplanation(scope.row)"
              >
                查看解析
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 学习建议 -->
    <!--<div class="suggestions-section">-->
      <!--<div class="section-header">-->
        <!--<h3>学习建议</h3>-->
      <!--</div>-->
      <!---->
      <!--<div class="suggestions-content">-->
        <!--<div class="suggestion-item">-->
          <!--&lt;!&ndash;<div class="suggestion-icon">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-icon><Lightbulb /></el-icon>&ndash;&gt;-->
          <!--&lt;!&ndash;</div>&ndash;&gt;-->
          <!--<div class="suggestion-text">-->
            <!--<h4>错题复习策略</h4>-->
            <!--<p>建议按照错误次数从多到少的顺序复习，重点关注多次错误的题目。每道题复习后，可以标记为已掌握，系统会减少该题目的出现频率。</p>-->
          <!--</div>-->
        <!--</div>-->
        <!---->
        <!--<div class="suggestion-item">-->
          <!--<div class="suggestion-icon">-->
            <!--<el-icon><Clock /></el-icon>-->
          <!--</div>-->
          <!--<div class="suggestion-text">-->
            <!--<h4>复习时间安排</h4>-->
            <!--<p>建议每天安排30-60分钟专门复习错题，保持学习的连续性。错题复习是提高成绩最有效的方法之一。</p>-->
          <!--</div>-->
        <!--</div>-->
        <!---->
        <!--<div class="suggestion-item">-->
          <!--&lt;!&ndash;<div class="suggestion-icon">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-icon><Target /></el-icon>&ndash;&gt;-->
          <!--&lt;!&ndash;</div>&ndash;&gt;-->
          <!--<div class="suggestion-text">-->
            <!--<h4>重点突破</h4>-->
            <!--<p>分析错题类型分布，找出您的薄弱环节。针对性地进行专项练习，可以快速提升相关领域的掌握程度。</p>-->
          <!--</div>-->
        <!--</div>-->
      <!--</div>-->
    <!--</div>-->
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Warning, 
  RefreshRight, 
  Check, 
  TrendCharts,
//  Lightbulb,
  Clock,
//  Target
} from '@element-plus/icons-vue'
import { getWrongQuestions,examstypeList,getQuestionId } from '@/api/system'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const wrongQuestions = ref([])
const selectedQuestions = ref([])
const stats = ref({
  totalWrongQuestions: 0,
  reviewedQuestions: 0,
  masteredQuestions: 0,
  masteryRate: 0
})

// 筛选参数
const filterParams = ref({
  examType: '',
  questionType: '',
  wrongCount: '',
  keyword: ''
})

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 计算属性
const emptyText = computed(() => {
  if (loading.value) return '加载中...'
  if (filterParams.value.keyword || filterParams.value.examType || filterParams.value.questionType || filterParams.value.wrongCount) {
    return '没有找到符合条件的错题'
  }
  return '暂无错题记录'
})

// 获取错题集
const fetchWrongQuestions = async () => {
//  loading.value = true
//  try {
    // 使用mock数据
    const mockWrongQuestions = [
      {
        id: 1,
        questionId: 'q001',
        examName: '日语N5基础语法考试',
        examType: 'JLPT',
        questionType: 'singleChoice',
        question: {
          content: '「は」和「が」的区别是什么？',
          correctAnswer: '「は」表示主题，「が」表示主语',
          explanation: '「は」用于提示主题，表示要谈论的话题；「が」用于表示动作的主体或状态的主体。'
        },
        userAnswer: '「は」表示主语，「が」表示主题',
        wrongCount: 2,
        lastWrongDate: '2024-01-15T10:00:00Z',
        reviewed: false,
        mastered: false
      },
      {
        id: 2,
        questionId: 'q002',
        examName: '商务日语会话考试',
        examType: '特定技能',
        questionType: 'singleChoice',
        question: {
          content: '在商务场合，如何礼貌地拒绝邀请？',
          correctAnswer: '「申し訳ございませんが、今回は参加できません」',
          explanation: '在商务场合，应该使用敬语表达歉意，并说明无法参加的原因。'
        },
        userAnswer: '「参加しません」',
        wrongCount: 1,
        lastWrongDate: '2024-01-10T14:00:00Z',
        reviewed: true,
        mastered: false
      },
      {
        id: 3,
        questionId: 'q003',
        examName: '日语听力理解考试',
        examType: 'JLPT',
        questionType: 'singleChoice',
        question: {
          content: '听力材料中提到的会议时间是？',
          correctAnswer: '下午2点',
          explanation: '听力材料中明确提到了「午後2時」这个时间。'
        },
        userAnswer: '上午10点',
        wrongCount: 3,
        lastWrongDate: '2024-01-05T09:00:00Z',
        reviewed: false,
        mastered: false
      },
      {
        id: 4,
        questionId: 'q004',
        examName: '日语阅读理解考试',
        examType: 'JLPT',
        questionType: 'singleChoice',
        question: {
          content: '文章的主要观点是什么？',
          correctAnswer: '环保意识的重要性',
          explanation: '文章通过多个例子说明了环保意识在现代社会中的重要性。'
        },
        userAnswer: '经济发展的必要性',
        wrongCount: 1,
        lastWrongDate: '2023-12-25T13:00:00Z',
        reviewed: true,
        mastered: true
      },
      {
        id: 5,
        questionId: 'q005',
        examName: 'JFT基础考试',
        examType: 'JFT',
        questionType: 'multipleChoice',
        question: {
          content: '以下哪些是日语的基本敬语？',
          correctAnswer: ['です', 'ます', 'ございます'],
          explanation: 'です、ます、ございます是日语中最基本的敬语形式，用于表示礼貌。'
        },
        userAnswer: ['です', 'ます'],
        wrongCount: 2,
        lastWrongDate: '2024-01-01T15:00:00Z',
        reviewed: false,
        mastered: false
      },
      {
        id: 6,
        questionId: 'q006',
        examName: '日语写作表达考试',
        examType: '特定技能',
        questionType: 'fillBlank',
        question: {
          content: '请填写正确的助词：私は学生___です。',
          correctAnswer: 'です',
          explanation: '「です」是日语中表示断定的敬语助动词，用于句末。'
        },
        userAnswer: 'だ',
        wrongCount: 1,
        lastWrongDate: '2023-12-28T11:00:00Z',
        reviewed: true,
        mastered: false
      }
    ]
    const res  = await getWrongQuestions({
      examId:'',
      examTypeId: filterParams.value.examType,
      wrongNums: filterParams.value.wrongCount,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
    })
    // 模拟筛选
//    let filtered = res.rows
//
//    if (filterParams.value.examType) {
//      filtered = filtered.filter(q => q.examType === filterParams.value.examType)
//    }
//
//    if (filterParams.value.questionType) {
//      filtered = filtered.filter(q => q.questionType === filterParams.value.questionType)
//    }
//
//    if (filterParams.value.wrongCount) {
//      const count = parseInt(filterParams.value.wrongCount)
//      filtered = filtered.filter(q => q.wrongCount >= count)
//    }
//
//    if (filterParams.value.keyword) {
//      filtered = filtered.filter(q =>
//        q.question.content.toLowerCase().includes(filterParams.value.keyword.toLowerCase()) ||
//        q.examName.toLowerCase().includes(filterParams.value.keyword.toLowerCase())
//      )
//    }
    
//    // 模拟分页
//    const start = (pagination.value.pageNum - 1) * pagination.value.pageSize
//    const end = start + pagination.value.pageSize
    wrongQuestions.value = res.rows
    pagination.value.total = res.total
    
    // 计算统计数据
    calculateStats()
    
//  } catch (error) {
//    console.error('获取错题集失败:', error)
//    ElMessage.error('获取错题集失败，请稍后重试')
//  } finally {
//    loading.value = false
//  }
}

// 计算统计数据
const calculateStats = () => {
  const total = wrongQuestions.value.length
  const reviewed = wrongQuestions.value.filter(q => q.reviewed).length
  const mastered = wrongQuestions.value.filter(q => q.mastered).length
  
  stats.value = {
    totalWrongQuestions: total,
    reviewedQuestions: reviewed,
    masteredQuestions: mastered,
    masteryRate: total > 0 ? Math.round((mastered / total) * 100) : 0
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1
  fetchWrongQuestions()
}

// 重置筛选
const resetFilter = () => {
  filterParams.value = {
    examType: '',
    questionType: '',
    wrongCount: '',
    keyword: ''
  }
  pagination.value.pageNum = 1
  fetchWrongQuestions()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.pageNum = 1
  fetchWrongQuestions()
}

const handleCurrentChange = (page) => {
  pagination.value.pageNum = page
  fetchWrongQuestions()
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedQuestions.value = selection
}

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'singleChoice': '单选题',
    'multipleChoice': '多选题',
    'trueFalse': '判断题',
    'fillBlank': '填空题'
  }
  return typeMap[type] || '其他类型'
}

// 格式化答案
const formatAnswer = (answer, type) => {
  if (!answer) return '未作答'

  return answer
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN')
}

// 复习题目
const reviewQuestion = (question) => {
  router.push({
    path: '/question-review',
    query: { questionId: question.questionId,userAnswer: question.wrongAnswer }
  })
}

const changeSelect  = (str)=>{
  switch (str) {
    case 'A':
      return 'option_a'
    case 'B':
      return 'option_b'
    case 'C':
      return 'option_c'
    case 'D':
      return 'option_d'
    default:
      return ''
  }

}

// 查看解析
const viewExplanation = async(obj) => {
  const res  = await getQuestionId(obj.questionId)

  const userAnswer = obj.wrongAnswer + ' ' +res?.data?.[changeSelect(obj.wrongAnswer)]
  const correctAnswer= res?.data?.answer + ' ' +res?.data?.[changeSelect(res?.data?.answer)]
  ElMessageBox.alert(
    `<div><strong>题目：</strong>${res?.data?.content}</div><br>
     <div><strong>正确答案：</strong>${correctAnswer}</div><br>
     <div><strong>您的答案：</strong>${userAnswer}</div><br>
     <div><strong>解析：</strong>${res?.data?.remark || '暂无解析'}</div>`,
    '题目解析',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
}

// 批量复习
const batchReview = () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请先选择要复习的题目')
    return
  }
  
  ElMessage.success(`已选择 ${selectedQuestions.value.length} 道题目进行复习`)
  // 这里可以实现批量复习逻辑
}

// 导出错题
const exportWrongQuestions = () => {
  ElMessage.success('导出功能开发中')
}

const examTypes = ref([])
// 获取考试类型
const fetchLists = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
    }

    const response = await examstypeList(params)
    if (response.code === 200) {
      examTypes.value = response.rows || []
    } else {
    }
  } catch (error) {
    console.error('获取考试类型列表失败:', error)
  } finally {
  }
}

onMounted(() => {
  fetchWrongQuestions()
  fetchLists()
})
</script>

<style scoped>
.wrong-questions-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h2 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  margin: 0;
  font-size: 1.1rem;
}

.filter-section {
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 0 20px;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-section {
  max-width: 1200px;
  margin: 0 auto 30px;
  padding: 0 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  font-size: 2.5rem;
  color: #409EFF;
}

.stat-content h3 {
  margin: 0 0 5px 0;
  font-size: 2rem;
  color: #2c3e50;
}

.stat-content p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.questions-section {
  max-width: 1200px;
  margin: 0 auto 40px;
  padding: 0 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.questions-table {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.exam-name {
  display: flex;
  align-items: center;
  gap: 12px;
}

.exam-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
}

.exam-title {
  font-weight: 500;
  color: #2c3e50;
}

.exam-type {
  font-size: 0.8rem;
  color: #666;
  margin-top: 2px;
}

.question-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-text {
  color: #2c3e50;
  line-height: 1.5;
  font-size: 0.95rem;
}

.question-meta {
  display: flex;
  gap: 8px;
}

.user-answer {
  color: #F56C6C;
  font-weight: 500;
}

.correct-answer {
  color: #67C23A;
  font-weight: 500;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 30px;
}

.suggestions-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.suggestions-content {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #eee;
}

.suggestion-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.suggestion-icon {
  color: #E6A23C;
  font-size: 1.5rem;
  margin-top: 5px;
}

.suggestion-text h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 1.1rem;
}

.suggestion-text p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .suggestion-item {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
